<?php
declare(strict_types=1);

namespace app\common\lib\sms;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use think\facade\Log;

class QqSms implements SmsBase
{
    public static function sendCode(string $phone, int $code): bool
    {
        try {

            $cred = new Credential(config("qq.access_Key_Id"), config("qq.access_Key_Secret"));
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint(config("qq.host"));

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SmsClient($cred, config("qq.region_Id"), $clientProfile);

            $req = new SendSmsRequest();

            $params = [
                "PhoneNumberSet" => ["+86$phone"],
                "TemplateID" => config("qq.template_ID"),
                "Sign" => config("qq.sign_name"),
                "TemplateParamSet" => ["$code"],
                "SmsSdkAppid" => config("qq.sms_Sdk_Appid")
            ];
            $params = json_encode($params, 320);
            $req->fromJsonString($params);
            $resp = $client->SendSms($req);
            Log::info("qqsms-sendCode-{$phone}res" . json_encode($resp->toJsonString()));
        } catch (TencentCloudSDKException $e) {
            Log::error("qqsms-sendCode-{$phone}error" . $e->getErrorMessage());
            return false;
        }
        if (isset($resp->SendStatusSet[0]->Code) && $resp->SendStatusSet[0]->Code == "Ok") {
            return true;
        }
        return false;

    }
}